<?php
/**
 * Joomla! 1.5 component NS Pro
 *
 * @version $Id: nspro.php 2009-04-28 01:47:12 svn $
 * @author Christopher Mavros
 * @package Joomla
 * @subpackage NS Pro
 * @license GNU/GPL
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

class NsproModelNewsletters extends JModel {
    function __construct()
    {
        parent::__construct();

        //global $mainframe, $option;
        $mainframe = JFactory::getApplication();
        $option = JRequest::getCmd('option');

        $filter_order     = $mainframe->getUserStateFromRequest(  $option.'nsl.filter_order', 'filter_order', 'id', 'cmd' );
        $filter_order_Dir = $mainframe->getUserStateFromRequest( $option.'nsl.filter_order_Dir', 'filter_order_Dir', 'asc', 'word' );

        $this->setState('nsl.filter_order', $filter_order);
        $this->setState('nsl.filter_order_Dir', $filter_order_Dir);

        $array = JRequest::getVar('cid',  0, '', 'array');
        $this->setId((int)$array[0]);
    }

    function setId($id)
    {
        // Set id and wipe data
        $this->_id      = $id;
        $this->_data    = null;
    }

    function getNewsletter()
    {
        $db =& JFactory::getDBO();
        // Load the data
        if (empty( $this->_data )) {
            $query = ' SELECT * FROM `#__nspro_newsletters` '.
                    '  WHERE `id` = '.$this->_id;
            $db->setQuery( $query );
            $this->_data = $db->loadObject();
        }
        if (!$this->_data) {
            $this->_data = new stdClass();
            $this->_data->id = 0;
            $this->_data->fName  = null;
            $this->_data->fEmail = null;
            $this->_data->subject = null;
            $this->_data->message = null;
            $this->_data->datetime = null;
            $this->_data->sent = false;
            $this->_data->mailing_lists = null;
            $this->_data->emails_per_send = 0;
            $this->_data->LastID = 0;
            $this->_data->is_scheduled = 0;
            $this->_data->scheduledatetime = null;
        }
        return $this->_data;
    }

    function getNewsletterById($id)
    {
        $db =& JFactory::getDBO();

        $query = ' SELECT * FROM `#__nspro_newsletters` '.
                 '  WHERE id = "'.mysql_escape_string($id) . '"';
        $db->setQuery( $query );
        $ndata = $db->loadObject();
        return $ndata;
    }

    function getNewsletters($limit, $limitstart, $filterlist = 0) {
        $db =& JFactory::getDBO();

        $query = 'SELECT * FROM `#__nspro_newsletters`';
        if ($filterlist == -1) {
          $query = $query . ' WHERE `mailing_lists` = ""';
        }
        else if ($filterlist > 0) {
          $query = $query . ' WHERE (FIND_IN_SET("'.mysql_escape_string($filterlist).'", `mailing_lists`) > 0)';
        }
        $orderby = $this->_buildContentOrderBy();
        $query .= ' '.$orderby;

        $newsletterss = $this->_getList( $query , $limitstart, $limit);

        return $newsletterss;
    }

    function getNewslettersCount($filterlist = 0) {
        $db =& JFactory::getDBO();

        $query = 'SELECT COUNT(*) FROM `#__nspro_newsletters` ';
        if ($filterlist == -1) {
          $query = $query . 'WHERE `mailing_lists` = ""';
        }
        else if ($filterlist > 0) {
          $query = $query . 'WHERE (FIND_IN_SET("'.mysql_escape_string($filterlist).'", `mailing_lists`) > 0)';
        }

        $db->setQuery( $query );
        $nCount = $db->loadResult();

        return $nCount;
    }

    function store()
    {
        $db =& JFactory::getDBO();
        $row =& $this->getTable('nsnewsletters');
        //$data = JRequest::get( 'post' );
        $data = $_POST;
        $data['fName'] = stripcslashes($data['fName']);
        $data['subject'] = stripcslashes($data['subject']);
        $data['message'] = stripcslashes($data['message']);
        $data["scheduledatetime"] = date('Y-m-d H:i:s', strtotime($data["scheduledatetime"]));        

        // Bind the form fields to the nsnewsletters table
        if (!$row->bind($data)) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        // Make sure the nsnewsletters records are valid
        if (!$row->check()) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        // Store the nsnewsletters table to the database
        if (!$row->store()) {
            $this->setError( $row->getErrorMsg() );
            return false;
        }

        return true;
    }

    function delete()
    {
        $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

        $row =& $this->getTable('nsnewsletters');

        if (count( $cids ))
        {
            foreach($cids as $cid) {
                if (!$row->delete( $cid )) {
                    $this->setError( $row->getErrorMsg() );
                    return false;
                }
                else {
                  $db =& JFactory::getDBO();
                  
                  $db->setQuery('DELETE FROM `#__newsletter_openings` WHERE `nid` = "'.mysql_escape_string($cid).'"');
                  $db->query();
                  
                  $db->setQuery('DELETE FROM `#__newsletter_attachments` WHERE `newsletter_id` = "'.mysql_escape_string($cid).'"');
                  $db->query();
                }
            }
        }
        return true;
    }

    function clearsending() {
      $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

      $row =& $this->getTable('nsnewsletters');
      $db =& JFactory::getDBO();

      if (count( $cids )) {
        foreach($cids as $cid) {
          $mnewsletter = $this->getNewsletterById($cid);
          if ($mnewsletter) {
            $query = 'UPDATE `#__nspro_newsletters` SET `sent`=0, `LastID`=0, `datetime`="0000-00-00 00:00:00" WHERE `id` = "' . mysql_escape_string($cid) . '"';
            $db->setQuery($query);
            $db->query();
          }
        }
      }
      return true;
    }

    function createduplicate() {
      $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

      $row =& $this->getTable('nsnewsletters');
      $db =& JFactory::getDBO();

      if (count( $cids )) {
        foreach($cids as $cid) {
          $mnsl = $this->getNewsletterById($cid);
          if ($mnsl) {
            $query = 'INSERT INTO `#__nspro_newsletters` (`fName`, `fEmail`, `subject`, `message`, `datetime`, `sent`, `mailing_lists`, `emails_per_send`, `LastID`) ';
            $query = $query . 'VALUES("' . mysql_escape_string($mnsl->fName) . '", "' . mysql_escape_string($mnsl->fEmail) . '", "' . mysql_escape_string($mnsl->subject) . '", "' . mysql_escape_string($mnsl->message) . '", "0000-00-00 00:00:00", 0, "' . mysql_escape_string($mnsl->mailing_lists) . '", "' . mysql_escape_string($mnsl->emails_per_send) . '", 0)';
            $db->setQuery($query);
            if (!$db->query()) {
              return false;
            }
          }
        }
      }
      return true;
    }

    function send() {

      $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

      $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

      include('components/com_nspro/lib.php');

			$jversion = new JVersion();
			$j15 = ($jversion->RELEASE == '1.5');
			if ($j15 != true) {
				jimport( 'joomla.html.parameter' );
			}

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      $component = JComponentHelper::getComponent( 'com_nspro' );
      $params = new JParameter( $component->params );

      $newsletter_delay = $params->get( 'newsletter_delay', '' );
      $maxtime_limit = $params->get('maxtime_limit', '300');

      $db =& JFactory::getDBO();
      $query = 'SELECT COUNT(*) FROM `#__nspro_subs` WHERE `confirmed` = 1';
      $db->setQuery($query);
      $mcount = $db->loadResult();

      if( !ini_get('safe_mode') ){
        if ($newsletter_delay != '') {
          $mtlim = $newsletter_delay * count($cids) * $mcount + 20;
          if ($mtlim < $maxtime_limit) {
            set_time_limit($mtlim);
          }
          else {
            set_time_limit($maxtime_limit);
          }
        }
        else {
          set_time_limit(0);
        }
      }
      
      // "Included as of NS Pro 1.3"
      ignore_user_abort(true);
      ob_start();
      print '<html>
<head>
<title>NS Pro Sending Page</title>
<meta HTTP-EQUIV="REFRESH" content="10; url=index.php?option=com_nspro&view=newsletters">
</head>
<body>
<center>
<div style="border: 1px solid #d5d5d5; background-color: #f9f9f9; width: 500px; font-size: 18px;">
<h3>NS Pro Sending Newsletter Page</h3>
<p>NS Pro has started sending the selected newsletter(s).</p>
<p>The Newsletter Manager will display the sending progress, in each Newsletter' . "'" . 's sending status, updated every time you refresh.</p>
<p>Redirecting you to the Newsletter Manager in 10 seconds.</p>
<img src="components/com_nspro/img/nspro-side-banner2.png">
</div>
</center>
</body>
</html>';

      $msize = ob_get_length();
      header("Content-Length: $msize");
      header('Connection: close');
      ob_end_flush();
      ob_flush();
      flush();
      // End of "Included as of NS Pro 1.3" 

      if (count($cids) > 0) {
        $errors = 0;
        $error_report = '';
        foreach($cids as $cid) {
          // for every newsletter
          $mnewsletter = $this->getNewsletterById($cid);

          $emails_per_send = $mnewsletter->emails_per_send;
          $mcount = GetSubCountByMailingLists($mnewsletter->mailing_lists, 1, $mnewsletter->LastID, 'id');
          $msubs = GetSubRowsByMailingLists($emails_per_send, $mnewsletter->mailing_lists, 1, $mnewsletter->LastID, 'id');

          $applySent = false;
          if ( ($emails_per_send == 0) || ($mcount <= $emails_per_send) ) {
            $n = count($msubs);
            $applySent = true;
          }
          else {
            $n = $emails_per_send;
          }
          
          // for each subscriber
          for ($i=0; $i < $n; $i++) {
            $msub = $msubs[$i];

            $mMessage = FilterNewsletterSmartText($msub[1], $msub[2], $mnewsletter->id, $mnewsletter->message, $msub[0]);

            $attachment = GetAttachmentsByNewsletterId($mnewsletter->id);

            if (MySendMailBounceHeader($mnewsletter->fEmail, $mnewsletter->fName, $msub[2], $mnewsletter->subject, $mMessage, true, null, null, $attachment) !== true) {
              $errors = $errors + 1;
              $error_report = JText::_('Error sending Newsletter ID:') . ' ' . $mnewsletter->id . ', ' . JText::_('Subscriber Email:') . ' ' . $msub[2] . ', '. JText::_('Date & Time:') . ' ' . date('r') . "\n";
              break;
            }
            else {
              $query = 'UPDATE `#__nspro_newsletters` SET `LastID` = "'.mysql_escape_string($msub[0]).'" WHERE `id` = "'.mysql_escape_string($cid).'"';
              $db->setQuery($query);
              $db->query();
            }

            if ( ($newsletter_delay != '') && ($newsletter_delay != 0) && ($newsletter_delay != '0')) {
              sleep($newsletter_delay);
            }
          }
          if ($error_report != '') {
            $target_file = JPATH_ADMINISTRATOR.DS."components/com_nspro/error_report.txt";
            $file = fopen($target_file, "a");
            if ($file !== false) {
              fwrite($file, $error_report);
              fclose($file);
            }
            // continue execution
          }
          if ($applySent == true) {
            $query = 'UPDATE `#__nspro_newsletters` SET `sent` = "1", `datetime` = "'.date('Y-m-d H:i:s').'" WHERE `id` = "'.mysql_escape_string($cid).'"';
            $db->setQuery($query);
            $db->query();
          }
        }
      }

      if ($errors > 0) {
        return $errors.' '.JText::_('newsletters could not be sent');
      }
      return true;
    }

    function _buildContentOrderBy() {
      //global $mainframe, $option;
      $mainframe = JFactory::getApplication();
      $option = JRequest::getCmd('option');

      $orderby = '';
      $filter_order     = $this->getState('nsl.filter_order');
      $filter_order_Dir = $this->getState('nsl.filter_order_Dir');

      if(!empty($filter_order) && !empty($filter_order_Dir) ){
        $orderby = ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
      }

      return $orderby;
    }

}
?>